package com.tdwyz.fictionmanage.controller;

import com.tdwyz.fictionmanage.pojo.FictionCategory;
import com.tdwyz.fictionmanage.pojo.Result;
import com.tdwyz.fictionmanage.service.FictionCategoryService;
import com.tdwyz.fictionmanage.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class FictionCategoryController {

    @Autowired
   private FictionCategoryService fictionCategoryService;
    @PostMapping
    public Result add(@RequestBody FictionCategory fictionCategory){
        int id = ThreadLocalUtil.getUserId();
        return Result.toAjax(fictionCategoryService.add(fictionCategory.getCategoryName(),fictionCategory.getCategoryAlias(),id));
    }

    //通过创建人获取分类
    @GetMapping
    public Result<List<FictionCategory>> get(){
        return Result.success(fictionCategoryService.get());
    }

    @GetMapping("listall")
    public Result<List<FictionCategory>> getall(){
        return Result.success(fictionCategoryService.getall());
    }

    //通过分类id获取id
    @GetMapping("/detail")
    public Result<FictionCategory> detail(@RequestParam Integer id){
        FictionCategory fictionCategory = fictionCategoryService.getCategoryById(id);
        if(fictionCategory == null){
            return Result.defeat("该分类不存在");
        }
        return Result.success(fictionCategory);
    }


    //删除代码
    @DeleteMapping
    public Result delete(@RequestParam Integer id){
        FictionCategory fictionCategory = fictionCategoryService.getCategoryById(id);
        if(fictionCategory == null){
            return Result.defeat("该分类不存在");
        }
        int userId = ThreadLocalUtil.getUserId();
        if(userId!=fictionCategory.getCreateUser()){
            return Result.defeat("无该分类删除权限");
        }
        return Result.success(fictionCategoryService.delete(id));
    }

    @PutMapping
    public Result update(@RequestBody FictionCategory fictionCategory){
        FictionCategory fictionCategoryByDb = fictionCategoryService.getCategoryById(fictionCategory.getId());
        if(fictionCategoryByDb == null){
            return Result.defeat("该分类不存在");
        }
        int userId = ThreadLocalUtil.getUserId();
        if(userId!=fictionCategoryByDb.getCreateUser()){
            return Result.defeat("无更新该分类权限");
        }
        return Result.toAjax(fictionCategoryService.update(fictionCategory));
    }

}
